import { Message } from 'element-ui';
import axios from 'axios';
import manager from "../store/modules/manager";
import router from "../router";
import store from '../store';
import helper from "../helper";
import constant from "../constants";

// 配合 sanctum 跨域时传递cookie
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// axios.defaults.headers.common['Content-Type'] = 'text/plain';

axios.interceptors.request.use((config) => {
    config.params = Object.assign(config.params || {}, {
        q: Math.random(),
    });
    if (document.title === constant.title.ONE_CLICK_LOGIN && store.state.manager.oneClickToken) {
        config.headers.Authorization = 'Bearer ' + store.state.manager.oneClickToken;
    } else if (store.state.manager.token) {
        config.headers.Authorization = 'Bearer ' + store.state.manager.token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

axios.interceptors.response.use((response) => {
    helper.setCache("lastRequestTime", parseInt(new Date().getTime() / 1000));
    // 抛出异常
    if (response.data && response.data.data && response.data.code) {
        Message.error('code: '+ response.data.code +' => '+response.data.message);
        return Promise.reject(response.data);
    }
    return response;

}, (error) => {
    if (error.response) {
        // 请求已发出，但服务器响应的状态码不在 2xx 范围内
        //console.log(error.response.data);
        //console.log(error.response.status);
        //console.log(error.response.headers);
        if (error.response.status === 401){
            // 清除缓存
            helper.clearCache();
            router.push({name: 'login'});
        }
        Message.error(error.response.data.message || 'error');
    } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
        Message.error(error.message || 'error');
    }

    return Promise.reject(error);
});

export default axios;
